import { reactive } from 'vue';
import axios from 'axios';

export interface DataType<T = unknown> {
  loading?: boolean;
  result: T | null;
}

export interface DataType2<T = unknown> {
  loading: 'init' | 'sending' | 'end';
  result: T | null;
}

export function useRequest<T = unknown>(url: string) {
  const data = reactive<DataType<T>>({
    loading: true,
    result: null
  });
  axios
    .get(url)
    .then((res) => {
      // console.log(res);
      data.result = res.data;
    })
    .catch((e) => console.log(e))
    .finally(() => {
      data.loading = false;
    });
  return data;
}

export function useRequest3<T = unknown>(url: string) {
  const data = reactive<DataType<T>>({
    loading: true,
    result: null
  });
  axios
    .get(url)
    .then((res) => {
      // console.log(res);
      data.result = res.data;
    })
    .catch((e) => console.log(e))
    .finally(() => {
      data.loading = false;
    });
  return data;
}

export function useRequest2<T = unknown>(url: string, data: DataType2<T>) {
  data.loading = 'sending';
  axios
    .get(url)
    .then((res) => {
      // console.log(res.data);
      data.result = res.data;
    })
    .catch((e) => console.log(e))
    .finally(() => {
      data.loading = 'end';
    });
}
